<template>
  <div class="container" ref="container">
    <div id="content" style="width: 800px; border: 1px solid #ccc;"></div>
    <div v-if="circleInput.visible">
      <div v-for="item in circleInput.data" :style="{
        position: 'absolute',
        left: item.position.x,
        top: item.position.y,
      }">
        <a-input-number type="number" min="1" max="20" v-model:value="item.molecular"> </a-input-number>
        <hr />
        <a-input-number type="number" min="1" max="20" v-model:value="item.denominator"
          @change="changeDenominator($event,item.ele)"></a-input-number>
      </div>
    </div>
    <div v-if="rectInput.visible">
      <div v-for="item in rectInput.data" :style="{
        position: 'absolute',
        left: item.position.x,
        top: item.position.y,
      }">
        <a-input-number type="number" min="1" max="20" v-model:value="item.molecular"> </a-input-number>
        <hr />
        <a-input-number type="number" min="1" max="20" v-model:value="item.denominator"
          @change="changeDenominator($event,item.ele)"></a-input-number>
      </div>
    </div>
    <div v-if="lineInput.visible">
      <div v-for="item in lineInput.data" :style="{
        position: 'absolute',
        left: item.position.x,
        top: item.position.y,
      }">
        <a-input-number type="number" min="1" max="20" v-model:value="item.molecular"> </a-input-number>
        <hr />
        <a-input-number type="number" min="1" max="20" v-model:value="item.denominator"
          @change="changeDenominator($event,item.ele)"></a-input-number>
      </div>
    </div>

    <a-button type="primary" v-show="!isshowBack" class="back" @click="back">
      <template #icon>
        <LeftOutlined />
      </template>
      返回
    </a-button>
    <a-button type="primary" @click="addGroup">
      添加
    </a-button>
    <a-button type="danger" @click="addGroup">
      重置
    </a-button>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref, Ref, inject, onMounted, watch } from 'vue';
import { createStore } from '../store/app';
import { LeftOutlined } from '@ant-design/icons-vue';
import { handleStickImg, handleAddImg, handleAddBackground, handleDrag, handleDrawLine, handleCreate, createTrapezoid, createRect, createCircle } from './common'
import Konva from 'konva';
import { Circle } from 'konva/lib/shapes/Circle';
import { reactive } from 'vue';
export default defineComponent({
  props: {},
  components: {
    LeftOutlined,
  },
  setup(props) {
    const store = inject('store') as ReturnType<ReturnType<typeof createStore>>;
    const preset = computed(() => store.preset);



    const stage = ref(null as null | any)
    const layer = ref({} as Konva.Layer)
    const layerCircle = ref({} as Konva.Layer)
    const layerRect = ref({} as Konva.Layer)
    const layerLine = ref({} as Konva.Layer)
    const scrollLayers  = ref({} as Konva.Layer)
    const clickColor = computed(() => store.clickColor);
    const molecular = ref(1 as number)
    const Denominator = ref(1 as number)
    const cloenShape = ref(null as any)
    let verticalBar ={} as Konva.Rect
    const PADDING = 5;
    let circleInput = reactive({ visible: false, data: [] } as any)
    let rectInput = reactive({ visible: false, data: [] } as any)
    let lineInput = reactive({ visible: false, data: [] } as any)
    watch(preset, () => {
      initRender()
 
    }, { deep: true })
    onMounted(() => {
      initRender()
     
    })

  
    const isshowBack = computed(() => {
      console.log("ayer.value", layer.value);

      if (layer.value.attrs == undefined) {
        return false
      } else {
        layer.value.attrs.visible === true ? false : true
      }
    })
    function initRender() {
      if (stage.value) stage.value.destroy();
      clearArray(circleInput.data);
      clearArray(rectInput.data);
      clearArray(lineInput.data);
      console.log(circleInput,rectInput,lineInput);
      
      stage.value = new Konva.Stage({
        container: 'content',
        width: 800,
        height: 3000,
      });
      layer.value = new Konva.Layer();
      layerCircle.value = new Konva.Layer()
      layerRect.value = new Konva.Layer()
      layerLine.value = new Konva.Layer()
      scrollLayers.value = new Konva.Layer()
      stage.value.add(layer.value)
      stage.value.add(layerCircle.value)
      stage.value.add(layerRect.value)
      stage.value.add(layerLine.value)
      stage.value.add(scrollLayers.value)
      drawingShape()
      drawScroll()
    }
    function clearArray(arr) {
    if (Array.isArray(arr)) { // 检查是否为数组
        arr.splice(0, arr.length);
    }
}
    function drawScroll(){
   
      // verticalBar = new Konva.Rect({
      //   width: 10,
      //   height: 100,
      //   fill: 'deeppink',
      //   opacity: 0.8,
      //   x: stage.value.width() - PADDING - 10,
      //   y: PADDING,
      //   draggable: true,
      //   dragBoundFunc: function(pos) {
      //     pos.x = stage.value.width() - PADDING - 10;
      //     pos.y = Math.max(
      //       Math.min(pos.y, stage.value.height() - this.height() - PADDING),
      //       PADDING
      //     );
      //     return pos;
      //   }
      // });
      // scrollLayers.value.add(verticalBar);
      // scrollLayers.value.draw();
      // verticalBar.on('dragmove', function() {
      //   const availableHeight =stage.value.height() - PADDING * 2 - verticalBar.height();
      //   var delta = (verticalBar.y() - PADDING) / availableHeight;
      //   layerRect.value.y(-stage.value.height() * delta);
      //   layerRect.value.batchDraw();
      // });

    }
    function hideLayer(main, rect, circle, line) {
      layer.value.visible(main)
      layerCircle.value.visible(circle)
      layerRect.value.visible(rect)
      layerLine.value.visible(line)
    }
    function drawingShape() {
      hideLayer(true, false, false, false)
      preset.value.data.forEach(item => {
        if (item.name == "rect") {
          const { id, x, y, stroke, fill, strokeWidth, height, width, name, draggable, rotation, scaleX, scaleY, skewX, skewY  } = item
          const rect = createRect(id, x, y, stroke, fill, strokeWidth, height, width, name, draggable, rotation, scaleX, scaleY, skewX, skewY )
          layer.value.add(rect)
          rect.on('click tap', () => {
            hideLayer(false, true, false, false)
            rectInput.visible = true
          });
          const newX =height 
          const newY =width 
          const rect1 = createRect(id, newX,newY, stroke, fill, strokeWidth, height, width, name, draggable, rotation, scaleX, scaleY, skewX, skewY )
          layerRect.value.add(rect1)
        
          addShape(rect1)
        } else if (item.name == "circle") {
          const { id, x, y, stroke, fill, strokeWidth, radius, name, draggable, rotation, scaleX, scaleY, skewX, skewY} = item
        const circle = createCircle(id, x, y, stroke, fill, strokeWidth, radius, name, draggable, rotation, scaleX, scaleY, skewX, skewY)
        layer.value.add(circle)
        const newX =radius +30
        const newY =radius +30
        const circle1 = createCircle(id, newX, newY, stroke, fill, strokeWidth, radius, name, draggable, rotation, scaleX, scaleY, skewX, skewY)
        layerCircle.value.add(circle1)
        addShape(circle1)
        circle.on('click tap', () => {
          hideLayer(false, false, true, false)
           circleInput.visible = true
        }); 
        } else if (item.name == 'trapezoid') {
          const { id, x, y, stroke, strokeWidth, points, name, draggable, rotation, scaleX, scaleY, skewX, skewY } = item
          const trapezoid = createTrapezoid(id, x, y, stroke, strokeWidth, points, name, draggable, rotation, scaleX, scaleY, skewX, skewY)
          layer.value.add(trapezoid)
          trapezoid.on('click tap', () => {
            hideLayer(false, false, false, true)
            lineInput.visible = true
          });
          const trapezoid1 = createTrapezoid(id, 20, y, stroke, strokeWidth, points, name, false, rotation, scaleX, scaleY, skewX, skewY)
          layerLine.value.add(trapezoid1)
          addShape(trapezoid1)
        }
      })
    }

    function back() {
      hideLayer(true, false, false, false)
      circleInput.visible = false
      rectInput.visible = false
      lineInput.visible = false
    }
    function addShape(ele) {
      if (ele instanceof Konva.Rect) {
        const ciclePosition = ele.getAbsolutePosition();
      const stageBox = stage.value.container().getBoundingClientRect();
      const areaPosition = {
        x: stageBox.left + ciclePosition.x  + 300,
        y: stageBox.top + ciclePosition.y
      };
        rectInput.data.push({
          ele:ele,
          position: {
            x: areaPosition.x + 'px',
            y: areaPosition.y + 'px',
          },
          molecular: 1,
          denominator: 1,
        })
      } else if (ele instanceof Konva.Circle) {
        const ciclePosition = ele.getAbsolutePosition();
      const stageBox = stage.value.container().getBoundingClientRect();
      const areaPosition = {
        x: stageBox.left + ciclePosition.x + 300,
        y: stageBox.top + ciclePosition.y -ele.attrs.radius
      };
        circleInput.data.push({
          ele:ele,
          position: {
            x: areaPosition.x + 'px',
            y: areaPosition.y + 'px',

          },
          molecular: 1,
          denominator: 1,
        })
      } else if (ele instanceof Konva.Line) {
        const ciclePosition = ele.getAbsolutePosition();
      const stageBox = stage.value.container().getBoundingClientRect();
      const areaPosition = {
        x: stageBox.left + ciclePosition.x + 500,
        y: stageBox.top + ciclePosition.y 
      };
        lineInput.data.push({
          ele:ele,
          position: {
            x: areaPosition.x + 'px',
            y: areaPosition.y + 'px',

          },
          molecular: 1,
          denominator: 1,
        })
      }

    }
    function addGroup(){
      console.log(11);
      
      if( rectInput.visible){
        const filterRect = layerRect.value.children.filter(item=>item?.attrs.name==="rect")
        const ele = filterRect[filterRect.length-1]
    
        const{ id, x, y, stroke, fill, strokeWidth, height, width, name, draggable, rotation, scaleX, scaleY, skewX, skewY } =   ele.attrs
      const newY = y +height*scaleY +20
      const rect = createRect(id, x, newY, stroke, fill, strokeWidth, height, width, name, draggable, rotation, scaleX, scaleY, skewX, skewY  )
      layerRect.value.add(rect)
      addShape(rect)
      }else if(circleInput.visible) {
        const ele = layerCircle.value.children[layerCircle.value.children.length-1]
      const{  id, x, y, stroke, fill, strokeWidth, radius, name, draggable, rotation, scaleX, scaleY, skewX, skewY } =   ele.attrs
      const newY = y +radius*2 +20
      const circle = createCircle( id, x, newY, stroke, fill, strokeWidth, radius, name, draggable, rotation, scaleX, scaleY, skewX, skewY)
      layerCircle.value.add(circle)
      console.log(layerCircle.value.children);
      
      addShape(circle)
      
       
      }else if(lineInput.visible){

        const ele = layerLine.value.children[layerLine.value.children.length-1]
        const { id, x, y, stroke, strokeWidth, points, name, draggable, rotation, scaleX, scaleY, skewX, skewY } =   ele.attrs
        const newY = y +100
      const line = createTrapezoid(id, x, newY, stroke, strokeWidth, points, name, draggable, rotation, scaleX, scaleY, skewX, skewY)
      layerLine.value.add(line)
      addShape(line)
      console.log(layerLine.value.children);
      }
    }
    function drawSelectedShape(shape) {
      if (shape instanceof Konva.Rect) {
        cloenShape.value = shape.clone({ y: 200 });
      } else if (shape instanceof Konva.Circle) {
        cloenShape.value = shape.clone({ y: 200 });
      } else if (shape instanceof Konva.Line) {
        cloenShape.value = shape.clone({ y: 200 });
      }
      cloenShape.value.off('click tap')
      layer.value.add(cloenShape.value);
      layer.value.draw();
    }
    function changeDenominator(e,ele) {
      console.log(e,ele);
      
      var denominator = e;
      if (!isNaN(denominator) && denominator > 0) {
        if (ele instanceof Konva.Rect) {
          divideRectangle(ele, denominator);
        } else if (ele instanceof Konva.Circle) {
          divideCircle(ele, denominator);
        } else if (ele instanceof Konva.Line) {
          divideLine(ele, denominator);
        }
      }
    }
    // 矩形等分
    function divideRectangle(rect, denominator) {

 // 考虑缩放后的宽度和高度
 var scaledWidth = rect.width() * rect.scaleX();
  var scaledHeight = rect.height() * rect.scaleY();
  
  // 计算每个子矩形的宽度
  var segmentWidth = scaledWidth / denominator;

  for (var i = 0; i < denominator; i++) {
    var segment = new Konva.Rect({
      // 考虑缩放后的 x 位置
      x: rect.x() + i * segmentWidth,
      y: rect.y(),
      width: segmentWidth, // 使用缩放后的宽度
      height: scaledHeight, // 使用缩放后的高度
      fill: 'white',
      stroke: rect.attrs.stroke,
      strokeWidth: 1
    });

    // 点击事件，用于改变颜色
    segment.on('click tap', function () {
      this.fill(this.fill() === 'white' ? clickColor.value : 'white');
      layerRect.value.draw();
    });

    // 将子矩形添加到图层
    layerRect.value.add(segment);
  }

  // 隐藏原始矩形
  rect.visible(false);
  layerRect.value.draw();
    }

    // 圆形等分
    function divideCircle(circle, denominator) {
  // 边界检查，确保分割数量合理
  if (denominator <= 1) return;

  // 计算每个扇形的角度
  var angleStep = 360 / denominator;
  var radius = circle.radius() * Math.max(circle.scaleX(), circle.scaleY()); // 考虑缩放

  for (var i = 0; i < denominator; i++) {
    var wedge = new Konva.Wedge({
      x: circle.x(),
      y: circle.y(),
      radius: radius,  // 使用考虑缩放后的半径
      angle: angleStep, // 每个扇形的角度
      rotation: i * angleStep, // 旋转角度
      fill: 'white',
      stroke: circle.attrs.stroke, // 保持原有的边框属性
      strokeWidth: 1
    });

    // 添加点击事件，点击后切换填充颜色
    wedge.on('click tap', function () {
      this.fill(this.fill() === 'white' ? clickColor.value : 'white');
      layerCircle.value.draw();
    });

    // 将分割后的扇形添加到图层中
    layerCircle.value.add(wedge);
  }

  // 隐藏原始的圆形
  circle.visible(false);
  layerCircle.value.draw();
}

    // 线段等分
    function divideLine(line, denominator) {
      //  边界检查，确保分割数量合理
 if (denominator <= 1) return;
      var points = line.points();
      var xStart = points[2];
      var xEnd = points[4];
      var y = points[3];
      var segmentLength = (xEnd - xStart) / denominator;
      console.log("segmentLength",segmentLength);
      console.log( layerLine.value.children.length);
      layerLine.value.children.forEach(item=>{
        if(item.name() === "line1") {
          item.destroy()
        }
      })
      for (let i = 0; i < layerLine.value.children.length; i++) {
        const item = layerLine.value.children[i];
        if(item.name() === "line1") {
          item.destroy()
        }
      }
      layer.value.batchDraw();
      console.log( layerLine.value.children.length);
    
      for (let i = 1; i < denominator; i++) {
        // 计算每个等分点的位置
        const xPos = xStart + i * segmentLength;
        // 在等分点处添加竖线
        const verticalLine = new Konva.Line({
          name:"line1",
          x:line.attrs.x,
          y:line.attrs.y,
          points: [xPos, y , xPos, y - 10],
          stroke: line.attrs.stroke,
          strokeWidth: line.attrs.strokeWidth
        });
       
        layerLine.value.add(verticalLine);
        
        verticalLine.on('click', function () {
          this.stroke(this.stroke() === 'black' ? 'yellow' : 'black');
          layerLine.value.batchDraw();
        });

     
      }
      layer.value.batchDraw();
      
      // line.visible(false);  // 删除原始线段
      // layer.value.draw();

    }




    return {
      molecular,
      Denominator,
      changeDenominator,
      preset,
      back,
      isshowBack,
      circleInput,
      rectInput,
      lineInput,
      addGroup
    };
  }
})
</script>

<style scoped lang="less">
[data-control="collageCharacters"] .container {
  box-sizing: border-box;
  position: relative;
  user-select: none;
  width: 100%;
  height: 100%;
  display: flex;
  overflow: hidden;

  .back {
    position: absolute;
    top: 0;
    left: 0
  }

  #drawing {
    position: absolute;
    width: 800px;
    height: 600px;
  }

  .dragging {
    position: absolute;
    pointer-events: none;
    display: inline-block;
    width: 100px;
    height: 100px;
    z-index: 1000;
  }

  #content {
    width: 800px;
    height: 100%;
    margin-right: 8px;
    box-shadow: 2px -1px 5px #ccc;
  }

  .prop-edit {
    width: 400px;
    height: 100%;
    box-shadow: 2px -1px 5px #ccc;

    .tab-item {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      align-items: baseline;
      height: 526px;
      background-color: #daeaea;
      overflow-y: auto;
      align-content: flex-start;

      .img-box {
        width: 100px;
        height: 100px;
        // border: 1px solid #ccc;
        margin: 6px;

        .materials-img {
          width: 100%;
          height: 100%;
          user-select: none;
        }
      }
    }
  }
}
</style>